package com.thisblog.homepage.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thisblog.common.core.base.BaseController;
import com.thisblog.common.core.result.Result;
import com.thisblog.common.core.result.ResultCode;
import com.thisblog.common.web.utils.RequestUtils;
import com.thisblog.homepage.common.enums.PermTypeEnum;
import com.thisblog.homepage.pojo.dto.UserDTO;
import com.thisblog.homepage.pojo.entity.SysUser;
import com.thisblog.homepage.pojo.entity.SysUserRole;
import com.thisblog.homepage.pojo.vo.UserVO;
import com.thisblog.homepage.service.ISysPermissionService;
import com.thisblog.homepage.service.ISysUserRoleService;
import com.thisblog.homepage.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/api.admin/v1/users")
@Slf4j
@AllArgsConstructor
public class UserController extends BaseController {

    private final ISysUserService iSysUserService;
    private final ISysUserRoleService iSysUserRoleService;

    private final ISysPermissionService iSysPermissionService;


    @ApiOperation(value = "用户详情")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/{id}")
    public Result detail(@PathVariable Long id) {
        SysUser user = iSysUserService.getById(id);
        if (user != null) {
            List<Long> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId, user.getId())
                    .select(SysUserRole::getRoleId)
            ).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            user.setRoleIds(roleIds);
        }
        return Result.success(user);
    }
    /**
     * 提供用于用户登录认证需要的用户信息
     * @param username
     * @return
     */
    @ApiOperation(value = "根据用户名获取用户信息")
    @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "path", dataType = "String")
    @GetMapping("/username/{username}")
    public Result getUserByUsername(@PathVariable String username) {
        SysUser user = iSysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        // 用户不存在，返回自定义异常，让调用端处理后续逻辑
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        // Entity->DTO
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user, userDTO);
        // 获取用户的角色ID集合
        List<Long> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, user.getId())
        ).stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        userDTO.setRoleIds(roleIds);
        return Result.success(userDTO);
    }


    @ApiOperation(value = "获取当前登陆的用户信息")
    @GetMapping("/me")
    public Result<UserVO> getCurrentUser() {
        log.info("获取当前登陆的用户信息 begin");

        UserVO userVO = new UserVO();

        // 用户基本信息
        Long userId = RequestUtils.getUserId();
        SysUser user = iSysUserService.getById(userId);
        BeanUtil.copyProperties(user, userVO);

        // 用户角色信息
        List<Long> roleIds = RequestUtils.getRoleIds();
        userVO.setRoles(roleIds);

        // 用户按钮权限信息
        List<String> perms = iSysPermissionService.listPermsByRoleIds(roleIds, PermTypeEnum.BUTTON.getValue());
        userVO.setPerms(perms);

        return Result.success(userVO);
    }
}
